//
//  LocationManager.m
//  evidenceGather
//
//  Created by 王继伟 on 13-9-10.
//  Copyright (c) 2013年 无. All rights reserved.
//

#import "LocationManager.h"
#import <CoreLocation/CoreLocation.h> 
#import <MapKit/MapKit.h>
#import "GDataXMLNode.h"
#import "FMDatabase.h"

@implementation LocationManager

@synthesize provCode;

 
-(id) init{
    locManager = [[CLLocationManager alloc] init];
    locManager.delegate = self;
    locManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locManager startUpdatingLocation];
    locManager.distanceFilter = 1000.0f;
    currentLatitude = [[NSString alloc]
                       initWithFormat:@"%g",
                       locManager.location.coordinate.latitude];
    currentLongitude = [[NSString alloc]
                        initWithFormat:@"%g",
                        locManager.location.coordinate.longitude];
    NSString * str1 = @"http://maps.google.com/maps/api/geocode/xml?latlng=";
    NSString * str2 = @",";
    NSString * str3 = @"&language=zh-CN&sensor=true";
    NSString * string = @"";
    string = [string stringByAppendingFormat:@"%@%@%@%@%@",str1,currentLatitude,str2,currentLongitude,str3];
    NSURL *url = [NSURL URLWithString:string]; 
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *citystring = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithXMLString:citystring options:0 error:nil];
    GDataXMLElement *root = [document rootElement];
    NSArray *children = [root children];
    if ([children count]>=4) { 
        GDataXMLElement  *channeName = [children objectAtIndex:1];
        GDataXMLElement *name = [[channeName children]objectAtIndex:5];
        GDataXMLElement * cityName1 = [[name children]objectAtIndex:1];
        NSString *provName = [cityName1 stringValue]; 
        //寻找路径
        NSString *doc_path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
        //数据库路径
        NSString *sqlPath=[doc_path stringByAppendingPathComponent:@"cityname.sqlite"];
        //原始路径
        NSString *orignFilePath = [[NSBundle mainBundle] pathForResource:@"cityname" ofType:@"sqlite"];
        NSFileManager *fm = [NSFileManager defaultManager];
        if([fm fileExistsAtPath:sqlPath] == NO){
            //如果doc下没有数据库，从bundle里面拷贝过来
            NSError *err = nil;
            if([fm copyItemAtPath:orignFilePath toPath:sqlPath error:&err] == NO){
                //如果拷贝失败
                NSLog(@"open database error %@",[err localizedDescription]);
            }
        }
        //初始化数据库
        FMDatabase *db=[FMDatabase databaseWithPath:sqlPath];
        //这个方法一定要执行
        if (![db open]) {
            NSLog(@"数据库打开失败！");
        }
        NSString *qrySql= @"select * from provinces where name='";
        qrySql=[qrySql stringByAppendingString:provName];
        qrySql=[qrySql stringByAppendingString:@"'"];
        FMResultSet *resultSet=[db executeQuery:qrySql];
        while ([resultSet next]) { 
            provCode = [resultSet stringForColumn:@"_id"];
        }
    }
    NSLog(@"prov code is %@",provCode);
    return self;
}
 
@end
